#!/usr/bin/python
import struct
import socket
import time
import sys

def getaddr(url) :
	p = url.find('://') #protocal
	if p != -1 :
		url = url[p + 3 :]
	
	p = url.find('/') #host
	if p != -1 :
		url = url[ : p]
	
	addr = socket.getaddrinfo(url, None)
	if addr is None :
		print >> stderr, "can find host: ", url
		return None
	return addr[0][4][0]

HOST, PORT = "localhost", 10029
MSG_HEAD_LEN = 12
MSG_ID = 1
MSG_TYPE = 0x00000001

urls = ('http://www.baidu.com', 'http://www.google.cn/webhp?source=g_cn', )

if len(sys.argv) > 1 :
	urls = []
	for url in sys.argv[1 : ] : 
		urls += [url]


items = []
for url in urls :
	addr = getaddr(url)
	if addr is None : 
		continue
	items += [{'addr':addr, 'url':url, 'cookie':''}]
print items

#[body]
msg_body = struct.pack('!H', len(items))
for item in items :
	msg_body += struct.pack('!HH16s%ds%ds' % (len(item['url']), len(item['cookie'])) , len(item['url']), len(item['cookie']), item['addr'], item['url'], item['cookie'])
if (len(item['url']) + len(item['cookie'])) % 2 :
	msg_body += '\x00';

#[head]
msg_head = struct.pack('!III', MSG_HEAD_LEN + len(msg_body), MSG_ID, MSG_TYPE)

print "HEAD:   %s" % msg_head.encode('hex')
print "BODY:   %s" % msg_body.encode('hex')
msg = msg_head + msg_body

#sys.exit(1)
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#raw_input("connect ...")

# Connect to server and send data
sock.connect((HOST, PORT))

#raw_input("send ...")
sock.send(msg)

# Receive data from the server and shut down
#received = sock.recv(1024)

#time.sleep(1);
raw_input("close ...")
sock.close()

#print "SENT:   %s" % msg
#print "RECV:   %s" % received

